(function () {

    "use strict";

    var api = {
        addAddress: "/api/caigou/apply",
        uploadUrl: "/api/caigou/upload"
    };
    sm.controller('wx-center-caigou-apply-controller', ['$scope', '$http', 'Modal', 'Toast', function ($scope, $http, Modal, Toast){

        var role = GetQueryString('role');

        if (role == 'purchaser') {
            location.href = '/center';
            return false
        }

        $scope.info = {
            "name": "",
            "phone": "",
            "email": "",
            "wechat": "",
            "company": "",
            "address": "",
            "license_url": "",
            "organization_url": "",
            "channel": ""
        };



        $scope.doApply = function() {

            if (!$scope.info.name || !$scope.info.phone || !$scope.info.email || !$scope.info.company ||
                !$scope.info.address || !$scope.info.license_url || !$scope.info.organization_url) {
                Modal.alert({
                    title: '操作提示',
                    content: "您有必填项请填写完整"
                });
                return;
            }

            $http.post(api.addAddress, $scope.info).success(function (data) {
                console.log(data);
            });
        };


        var uploader1 = WebUploader.create({
            server: api.uploadUrl,
            pick: "#up-license",
            auto: true,
            resize: false
        });

        uploader1.on('uploadProgress', function (file, process) {
            console.log(process);
        });

        uploader1.on('uploadSuccess', function (file, resp) {
            if (!resp.state) {
                var err = resp.error ? resp.error : "图片上传失败";
                Modal.alert({
                    title: '操作提示',
                    content: err
                });
                return null;
            }
            $scope.info.license_url = resp.data.key;
            setImage('up-license', resp.data.source)
        });

        var uploader2 = WebUploader.create({
            server: api.uploadUrl,
            pick: "#up-organization",
            auto: true,
            resize: false
        });

        uploader2.on('uploadProgress', function (file, process) {
            console.log(process);
        });

        uploader2.on('uploadSuccess', function (file, resp) {
            if (!resp.state) {
                var err = resp.error ? resp.error : "图片上传失败";
                Modal.alert({
                    title: '操作提示',
                    content: err
                });
                return null;
            }
            $scope.info.organization_url = resp.data.key;
            setImage('up-organization', resp.data.source)
        });

        function setImage(id, url) {
            $('#' + id).attr('style', 'background-image: url("' + url + '")');
        }

    }]);
})();

